﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Sage.DownloadLite.Core
{
    /// <summary>
    /// 下载配置
    /// </summary>
    public class DownloadConfiguration
    {
        /// <summary>
        /// 默认并发数量
        /// </summary>
        public const int DEFAULT_CONCURRENT_LIMIT = 3;
        /// <summary>
        /// 最大并发数量
        /// </summary>
        public const int MAX_CONCURRENT_LIMIT = 10;
        /// <summary>
        /// 默认超时时间（30分钟）
        /// </summary>
        public static readonly TimeSpan DEFAULT_TIMEOUT = TimeSpan.FromMinutes(30);
        /// <summary>
        /// 默认进度间隔（1%）
        /// </summary>
        public const double DEFAULT_PROGRESS_INTERVAL = 1.0;
        /// <summary>
        /// 默认用户代理字符串
        /// </summary>
        public const string DEFAULT_USER_AGENT = "Sage-DownloadManager/1.0";
        /// <summary>
        /// 并发数量限制
        /// </summary>
        public int ConcurrentLimit { get; set; } = DEFAULT_CONCURRENT_LIMIT;
        /// <summary>
        /// 下载超时时间
        /// </summary>
        public TimeSpan Timeout { get; set; } = DEFAULT_TIMEOUT;
        /// <summary>
        /// 进度更新间隔（百分比）
        /// </summary>
        public double ProgressInterval { get; set; } = DEFAULT_PROGRESS_INTERVAL;
        /// <summary>
        /// 用户代理字符串
        /// </summary>
        public string UserAgent { get; set; } = DEFAULT_USER_AGENT;

        /// <summary>
        /// 验证并修正配置参数
        /// </summary>
        public void ValidateAndCorrect()
        {
            // 验证并发数量
            if (ConcurrentLimit <= 0)
            {
                ConcurrentLimit = DEFAULT_CONCURRENT_LIMIT;
                DebugLogger.WriteMessage("Configuration",$"Invalid concurrent limit, reset to {DEFAULT_CONCURRENT_LIMIT}");
            }
            else if (ConcurrentLimit > MAX_CONCURRENT_LIMIT)
            {
                ConcurrentLimit = MAX_CONCURRENT_LIMIT;
                DebugLogger.WriteMessage("Configuration",$"Concurrent limit exceeds maximum, reset to {MAX_CONCURRENT_LIMIT}");
            }
            // 验证超时时间
            if (Timeout <= TimeSpan.Zero)
            {
                Timeout = DEFAULT_TIMEOUT;
                DebugLogger.WriteMessage("Configuration",$"Invalid timeout, reset to {DEFAULT_TIMEOUT}");
            }
            // 验证进度间隔
            if (ProgressInterval <= 0 || ProgressInterval > 100)
            {
                ProgressInterval = DEFAULT_PROGRESS_INTERVAL;
                DebugLogger.WriteMessage("Configuration",$"Invalid progress interval, reset to {DEFAULT_PROGRESS_INTERVAL}%");
            }
            // 验证用户代理
            if (string.IsNullOrWhiteSpace(UserAgent))
            {
                UserAgent = DEFAULT_USER_AGENT;
                DebugLogger.WriteMessage("Configuration",$"Invalid user agent, reset to {DEFAULT_USER_AGENT}");
            }
        }

    }
}
